/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package quan;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.DefaultDesktopManager;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;

/**
 *
 * @author Quannk
 */
public class QDesktopManager extends DefaultDesktopManager {
    @Override
    public void dragFrame(JComponent f, int x, int y) {
        if (f instanceof JInternalFrame) { // Deal only w/internal frames
            JInternalFrame frame = (JInternalFrame) f;
            JDesktopPane desk = frame.getDesktopPane();
            Dimension d = desk.getSize();

            // Nothing all that fancy below, just figuring out how to adjust
            // to keep the frame on the desktop.
            int newWidth = 0, newHeight = 0;
            if (x < 0) { // too far left?
                newWidth = x * -1 + frame.getWidth();
            } else {
                if (x + frame.getWidth() > d.width) { // too far right?
                    //x = d.width - frame.getWidth(); // flush against right side
                    newWidth = x + frame.getWidth() + 50;
                }
            }
            if (y < 0) { // too high?
                newHeight = x * -1 + frame.getHeight();
            } else {
                if (y + frame.getHeight() > d.height) { // too low?
                    //y = d.height - frame.getHeight(); // flush against the
                    // bottom
                    newHeight = y + frame.getHeight() + 50;
                }
            }
            if (newWidth > 0 && newHeight > 0) {
                desk.setPreferredSize(new Dimension(newWidth, newHeight));
                desk.setSize(newWidth, newHeight);
                Point p = new Point(x, y);
                Rectangle rectangle = new Rectangle(p, d);
                desk.scrollRectToVisible(rectangle);
            }
        }

        // Pass along the (possibly cropped) values to the normal drag handler.
        super.dragFrame(f, x, y);
    }
}
